package com.infra.micro.id.domain.advice;

import com.infra.common.exception.BizException;
import com.infra.common.resp.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionAdvice.class);

    /**
     * 处理所有不可知的异常
     */
    @ExceptionHandler(Throwable.class)
    public ResponseEntity handleException(Throwable e) {
        // 打印堆栈信息
        LOGGER.error("系统异常", e);
        return buildResponseEntity(Response.error("系统错误，请稍候重试或联系管理员"));
    }

    @ExceptionHandler(value = {IllegalArgumentException.class,
            BizException.class})
    public ResponseEntity handleIllegalArgumentException(RuntimeException e) {
        LOGGER.error("系统异常", e);
        return buildResponseEntity(Response.error(e.getMessage()));
    }

    /**
     * 统一返回
     */
    private ResponseEntity<Response> buildResponseEntity(Response response) {
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}
